package controllers

import (
	"github.com/astaxie/beego"
	"time"
	"strconv"
	"github.com/qiniu/api.v7/auth/qbox"
	"github.com/qiniu/api.v7/storage"
	"fmt"
	"context"
	"mime/multipart"
	"bytes"
	"io/ioutil"
	"models"
)

type FileApi struct {
	beego.Controller
}

var (
	//设置上传到的空间
	//bucket     = "snso"
	//ACCESS_KEY = "YwUhM_hu__HQUxmwdOCCEASoQbEqrExHNcOuBF_F"
	//SECRET_KEY = "sTvSUv3A8uSI7lQ58mYG4AnCZxOeoKy3z9V7xjOq"

	bucket     = "download-bbgstatic"
	ACCESS_KEY = "0tm25H4a_QUkt5frqYMVZF_60kOPy43Agirlegj0"
	SECRET_KEY = "_-OIJa9PRMywicyOaDnfnh5FzB32UGWqeWNPSbqu"
)

// @Title FileUpload
// @Description 上传文件
// @Param  uploadFile   patch File  true  string     文件File
// @Param  fileType   patch File  true  string     文件类型
// @Success 200 {object} models.User
// @Failure 400 Invalid params supplied
// @Failure 404 api not found
// @router /upload [post]
func (this *FileApi) FileUpload() {

	//ipAddress = beego.AppConfig.String("httphost")
	//port = beego.AppConfig.String("httpport")

	//if (len(ipAddress) <= 0) {
	//	logs.Error("文件服务器IP地址错误")
	//}

	f, fh, err := this.GetFile("uploadFile")

	defer func() {
		if f != nil {
			f.Close()
		}
	}()

	var BaseResult = new(models.BaseResult)

	if (f == nil) {

		BaseResult.Msg = "參數不能為空"
		BaseResult.Code = 100
		this.Data["json"] = BaseResult
		this.ServeJSON()
		return;
	}

	if err != nil {
		BaseResult.Msg = err.Error()
		BaseResult.Code = 100
	} else {

		//fileType := this.GetString("fileType")
		//var typePath = ""
		//
		//if (&fileType == nil) {
		//	typePath = "file/"
		//} else if (fileType == "image") {
		//	typePath = "image/"
		//} else if (fileType == "ring") {
		//	typePath = "ring/"
		//}

		name := strconv.FormatInt(time.Now().UnixNano(), 10) + fh.Filename

		err := QiniuUpload(f, name)

		if (err != nil) {
			BaseResult.Msg = err.Error()
			BaseResult.Code = 100
		} else {

			var image = new(models.File)
			image.FileName = name

			//image.FilePath = "http://omjjy36ny.bkt.clouddn.com/" + image.FileName
			image.FilePath = "http://7xj65l.com1.z0.glb.clouddn.com/" + image.FileName

			image.FileSize = fh.Size
			BaseResult.Data = image

		}
		//this.SaveToFile("uploadFile", "static/" + typePath + image.FileName)

	}
	this.Data["json"] = BaseResult
	this.ServeJSON()

}

func QiniuUpload(f multipart.File, fileName string) (error) {

	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}

	mac := qbox.NewMac(ACCESS_KEY, SECRET_KEY)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuadong
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	// 可选配置
	putExtra := storage.PutExtra{
		Params: map[string]string{
		//"x:name": "github logo",
		},
	}

	var data []byte

	data, _ = ioutil.ReadAll(f)

	//f.Read(data)

	dataLen := int64(len(data))

	fmt.Print("f:")
	fmt.Println(f)

	var key = fileName

	//var key  =strconv.FormatInt(time.Now().Unix(), 10)

	err := formUploader.Put(context.Background(), &ret, upToken, key, bytes.NewReader(data), dataLen, &putExtra)
	fmt.Println(ret.Key, ret.Hash)

	return err
}
